import { useI18n } from 'vue-i18n'

export interface ValidationResult {
	success: boolean
	errors?: string[]
}

export const useFormValidation = () => {
	const { t } = useI18n()

	const validateAll = async (editForm: any): Promise<ValidationResult> => {
		const errors: string[] = []

		// 验证基本信息
		if (!editForm.spu.name?.trim()) {
			errors.push(t('验证.商品名必填'))
		}
		if (!editForm.spu.categoryId) {
			errors.push(t('验证.商品类别必选'))
		}
		if (
			!editForm.spu.supplierId &&
			!(editForm.spu.createdByUser > 0 && editForm.spu.isSecondHand)
		) {
			errors.push(t('验证.请选择供应商'))
		}

		// 验证销售信息
		if (editForm.salesInfo.sort === undefined || editForm.salesInfo.sort === null) {
			errors.push(t('验证.排序值必填'))
		} else if (editForm.salesInfo.sort < 0 || editForm.salesInfo.sort > 999999) {
			errors.push(t('验证.排序值必须在0-999999之间'))
		}

		// 验证运费信息
		if (
			editForm.freightInfo.freightPrice === undefined ||
			editForm.freightInfo.freightPrice === null
		) {
			errors.push(t('验证.运费必填'))
		} else if (editForm.freightInfo.freightPrice < 0) {
			errors.push(t('验证.运费不能为负数'))
		}

		// 验证追加运费
		for (const item of editForm.freightInfo.remoteFreights) {
			if (!item.provinceId) {
				errors.push(t('验证.追加运费省份不能为空'))
				break
			}
			if (item.appendFreightPrice <= 0) {
				errors.push(t('验证.追加运费必须大于0'))
				break
			}
		}

		// 验证SKU信息
		if (editForm.skus.length === 0) {
			errors.push(t('验证.至少需要添加一个SKU'))
		} else {
			for (const sku of editForm.skus) {
				if (sku.sort < 0 || sku.sort > 999999) {
					errors.push(t('验证.SKU排序值超出取值范围', { min: 0, max: 999999 }))
					break
				}
			}
		}

		return errors.length === 0 ? { success: true } : { success: false, errors }
	}

	return { validateAll }
}
